package com.ruoyi.api.wechat.controller;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.JiajiaUser;
import com.ruoyi.system.domain.Singleton;
import com.ruoyi.system.service.IJiajiaMappointsService;
import com.ruoyi.system.service.IJiajiaUserService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.IWechatAuthService;
import com.ruoyi.system.utils.TokenUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/wechat")
public class WechatAuthController {

    private static final Logger logger = LoggerFactory.getLogger(WechatAuthController.class);

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String appSecret;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private IWechatAuthService wechatAuthService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IJiajiaMappointsService jiajiaMappointsService;

    @Autowired
    private IJiajiaUserService userService;

    private final static String MENU_CREATE_URL =" https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    /**
     * 获取基础accesstoken地址，get方式
     */
    public final static String token_Url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    @GetMapping("/getCode")
    public AjaxResult getCode() {
        try {
            String redirectUri = URLEncoder.encode("https://h5.baijixing.com.cn/api/wechat/silentLogin", "UTF-8"); // 回调地址
            String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize"
                    + "?appid=" + appId
                    + "&redirect_uri=" + redirectUri
                    + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            Map<String, String> params = new HashMap<>();
            Map<String, String> headers = new HashMap<>();
            String response = HTTPUtil.get(authUrl, params, headers);
            logger.info("微信静默登录返回结果：{}", response);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @GetMapping("/silentLogin")
    public AjaxResult silentLogin(@RequestParam(value = "code",required = false)String code) {

        try {
            // 1. 参数校验
            if (StringUtils.isEmpty(code)) {
                return AjaxResult.error("code不能为空");
            }
            // 2. 调用微信接口
            JSONObject result = WechatAuthUtil.getOpenIdByCode(appId, appSecret, code);
            // 3. 处理用户体系
            String openid = result.getString("openid");
            String refreshToken = result.getString("refresh_token");
            JSONObject accessTokenResponse =  WechatAuthUtil.getAccessToken(appId, "refresh_token", refreshToken);
            String refreshTokenKey =  accessTokenResponse.getString("access_token");
            JSONObject userInfo = WechatAuthUtil.getUserInfo(refreshTokenKey, openid);
            String nickname = userInfo.getString("nickname");
            String name = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
            String headimgurl = userInfo.getString("headimgurl");
            Integer sex = Integer.valueOf(userInfo.getString("sex"));
            String unionid = userInfo.getString("unionid");
            JiajiaUser jiajiaUser = new JiajiaUser();
            jiajiaUser.setUnionid(unionid);
            System.out.println("unionid"+unionid+"-----------------------------------------------------------------------");
            List<JiajiaUser> jiajiaUsers = userService.selectJiajiaUserList(jiajiaUser);
            if (jiajiaUsers.isEmpty()){
                JiajiaUser user = new JiajiaUser();
                user.setGzhOpenId(openid);
                user.setName(name);
                user.setAvatar(headimgurl);
                user.setSex(sex);
                user.setUnionid(unionid);
                int i = userService.insertJiajiaUser(user);
                user.setOpenId(unionid);
                return AjaxResult.success(user);
            }
            JiajiaUser user = jiajiaUsers.get(0);
            user.setName(name);
            user.setAvatar(headimgurl);
            user.setSex(sex);
            user.setGzhOpenId(openid);
            userService.updateJiajiaUser(user);
            user.setOpenId(unionid);
            return AjaxResult.success(user);
        }catch (Exception e){
            e.getMessage();
        }
        return AjaxResult.error("登录失败");
//        // 4. 生成登录态
//        String uuid = UUID.randomUUID().toString().replace("-","");
//        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid,user.getId()+"");

    }

    @GetMapping("/config")
    public ResponseEntity<?> getJsSdkConfig(@RequestParam String url) {
        try {
            Map<String, Object> config = WechatJsSdkUtil.generateConfig(appId, appSecret, url);
            return ResponseEntity.ok(config);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("errcode", e.getMessage()));
        }
    }


    @ApiOperation("登陆")
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String phone,
                            @RequestParam String code,
                            @RequestParam String openId,
                            @RequestParam String inviter) {
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error("手机号不能为空");
        }
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("验证码不能为空");
        }


            String realCode =  redisTemplate.opsForValue().get(TokenUtil.jiajia_user_phone_login_code +phone);
            if (StringUtils.isEmpty(realCode)){
                return AjaxResult.error("请先获取验证码");
            }
            if (!realCode.equals(code)){
                return AjaxResult.error("验证码不对");
            }

        if (StringUtils.isEmpty(openId)){
            return AjaxResult.error("openId不能为空");
        }

        JiajiaUser jiajiaUser = new JiajiaUser();
        jiajiaUser.setUnionid(openId);
        List<JiajiaUser> userList =  userService.selectJiajiaUserList(jiajiaUser);
        if (userList.isEmpty()){
            throw new RuntimeException("用户不存在");
        }
        JiajiaUser user = userList.get(0);
        user.setPhone(phone);
        user.setInviter(inviter);
        int i = userService.updateJiajiaUser(user);
        System.out.println(i+"userphone:"+user.getPhone());
        if (user.getDel().intValue() == 1)return AjaxResult.error("此账户已注销!");

        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid,user.getId()+"",60, TimeUnit.DAYS);
        return AjaxResult.success(uuid);
    }

    /**
     *jsonString:
     *{"button":[{"name":"社工通","type":"view","url":"https://h5.baijixing.com.cn"}]}
     */
    @ApiOperation("创建菜单")
    @PostMapping("/createMenu")
    public AjaxResult createMenu(String jsonString){
/*        List<Map<String,String>> list =new ArrayList<>();
        Map<String,String> map=new HashMap<>();
        map.put("type","view");
        map.put("name","社工通");
        map.put("url","https://h5.baijixing.com.cn");
        list.add(map);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("button",list);*/
        String accessToken = getAccessToken();

        createMenu(jsonString,accessToken);
        return null;
    }



    /**
     * 获取公众号的唯一秘钥，Accesstoken

     * @return	accessToken
     */
    public static String getAccessToken(){
        String appId="wx8c726aef4a4b511a";
        String secret="abb687c0db40849061cbf3f6f0b1c25a";
        //拼接请求地址
        String requestUrl = token_Url.replace("APPID", appId).replace("APPSECRET", secret);
        String accessToken = "";
        long token_time = Singleton.getInstance().getTokenTime();
        long nowTime = System.currentTimeMillis()/1000;

        //判断上次获取的accessToken是否有效，如果无效重新获取，并缓存
        if(0 == token_time || nowTime - token_time > 7000){
            //调用接口
            String jsonString = HttpRequest.httpRequest(requestUrl, "GET", null);
            try{
                //将json字符串转换成java对象
                JSONObject jsonObj = JSONObject.parseObject(jsonString);
                boolean err = jsonObj.containsKey("access_token");
                if(err){
                    accessToken = jsonObj.getString("access_token");
                    System.out.println("获取access_token: "+accessToken);
                }else{
                    accessToken = "";
                    System.out.println("获取access_token失败！"+jsonObj);
                }

                // 缓存accessToken
                Singleton.getInstance().setAccessToken(accessToken);
                Singleton.getInstance().setTokenTime(System.currentTimeMillis()/1000);

            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            accessToken = Singleton.getInstance().getAccessToken();
        }
        return accessToken;
    }


    public static boolean createMenu(String json,String accessToken){
        boolean result = false;
        //拼装请求地址
        String requestUrl = MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
        //调用接口
        String respjson = HttpRequest.httpRequest(requestUrl, "POST", json);
        //将JSONObject字符串转成对象
        JSONObject jsonobject = JSONObject.parseObject(respjson);
        if(jsonobject != null){
            int errCode = jsonobject.getIntValue("errcode");
            String errMsg = jsonobject.getString("errmsg");
            if(0 == errCode){
                result = true;
                System.out.println("创建菜单成功!");
            }else{
                result= false;
                System.out.println("创建菜单失败："+errCode);
            }
        }

        return result;
    }





}

